package base

import (
	"errors"
	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/model"
	"go.mongodb.org/mongo-driver/bson"
)

// 数据交互基础接口
type Repository interface {
	InitDB() error
	CheckDB() error
	CreateDB(name string) error
	SetCollectionName(name string)
	GetCollectionName() string

	Insert(mdl *model.DataUserModel) error
	Delete(mdl *model.DataUserModel) error
	BatchDelete(mdl *model.DataUserModel) error
	DeleteLogic(mdl *model.DataUserModel) error
	BatchDeleteLogic(mdl *model.DataUserModel) error
	Update(mdl *model.DataUserModel) error
	Find(mdl *model.DataUserModel) (interface{}, error)
	FindOne(mdl *model.DataUserModel) (interface{}, error)
	Count(mdl *model.DataUserModel) (int64, error)

}

type RepositoryStruct struct {
	Mongo          *helper.Mongo
	CollectionName string
}

func (repo *RepositoryStruct) InitDB() (err error) {
	if repo.Mongo != nil {
		return nil
	}
	repo.Mongo, err = server.Mongo()
	return err
}

func (repo *RepositoryStruct) CheckDB() error {
	if repo.CollectionName == "" {
		return errors.New("collection name can not be empty")
	} else if repo.Mongo == nil {
		return repo.InitDB()
	}
	return nil
}

func (repo *RepositoryStruct) CreateDB(name string) (err error) {
	err = repo.InitDB()
	repo.CollectionName = name
	return err
}

func (repo *RepositoryStruct) SetCollectionName(name string) {
	repo.CollectionName = name
}

func (repo *RepositoryStruct) GetCollectionName() string {
	return repo.CollectionName
}

func (repo *RepositoryStruct) Insert(model *model.DataUserModel) error {
	_, err := repo.Mongo.InsertOne(repo.CollectionName, model)
	return err
}
func (repo *RepositoryStruct) Delete(model *model.DataUserModel) error {
	_, _ = repo.Mongo.DeleteMany(repo.CollectionName, model)
	return nil
}
func (repo *RepositoryStruct) DeleteLogic(model *model.DataUserModel) error {
	_, _ = repo.Mongo.DeleteMany(repo.CollectionName, model)
	return nil
}
func (repo *RepositoryStruct) Update(model *model.DataUserModel) error {
	_, _ = repo.Mongo.UpdateOne(repo.CollectionName, model, model)
	return nil
}
func (repo *RepositoryStruct) Find(model *model.DataUserModel) (interface{}, error) {
	var result interface{}
	_ = repo.Mongo.FindMany(repo.CollectionName, model, result)
	return []interface{}{}, nil
}
func (repo *RepositoryStruct) FindOne(model *model.DataUserModel) (interface{}, error) {
	var result interface{}
	_, _ = repo.Mongo.FindOne(repo.CollectionName, model, result)
	return nil, nil
}
func (repo *RepositoryStruct) Count(mdl *model.DataUserModel) (int64, error) {
	if err := repo.CheckDB(); err != nil {
		return 0, err
	}
	filter := bson.M{}
	if mdl.Filter != nil {
		filter = *mdl.Filter
	}
	return repo.Mongo.Count(repo.CollectionName, filter)
}

func (repo *RepositoryStruct) BatchDelete(mdl *model.DataUserModel) error {
	return nil
}

func (repo *RepositoryStruct) BatchDeleteLogic(mdl *model.DataUserModel) error {
	return nil
}
